/* 享元模式 */

use std::collections::HashMap;
use std::cell::RefCell;

/// 部门对象，一种用于共享的角色
#[derive(Clone)]
pub struct Department {
    name: String
}

impl Department {
    fn new(name: &str) -> Department {
        println!("花费大量时间:创建[{}]部门", name);
        Department {
            name: String::from(name)
        }
    }
}

/// 部门工厂，用于提供部门的实例
pub struct DepartmentFactory {
    map: RefCell<HashMap<String, Department>>
}



impl DepartmentFactory {
    /// 根据部门名称获取部门的实例
    fn get_department(&self, name: &str) -> Department{
        println!("获取[{}]部门", name);
        let mut map = self.map.borrow_mut();
        let op = map.get(&String::from(name));
        match op {
            Some(dept) => dept.clone(),
            None => {
                let dept = Department::new(name);
                let result = dept.clone();
                map.insert(String::from(name), dept);
                result
            }
        }

    }

    fn new() -> DepartmentFactory {
        DepartmentFactory {
            map: RefCell::new(HashMap::new())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_flyweight_1() {
        let df = DepartmentFactory::new();

        df.get_department("财务");
        df.get_department("行政");
        df.get_department("财务");
        df.get_department("销售");
        df.get_department("销售");
    }
}